(function(){
	jQuery.mds = {
		builder : function (pageId, params, callback){
			
			//0、初始化函数
			var init = function (){
				createTools();createCanvas(); createControlList(); createPropertices();
			};
			
			//1、创建左侧控件列表
			var createControlList = function (){
				
				$("#build_left li:first").attr("class", "tab_check");
				$('#tab_centent').children(':not(:first)').hide();
				
				$("#build_left>li").on("click",function() {
					$("#build_left li").not(this).attr("class", "");
					$('#tab_centent').children().hide();
					$(this).attr("class", "tab_check");
					$('#' + $(this).children('a:first').attr('tabid')).show();
				});
				
				var dblCheckObj, checkObj;	//定义双击对象和点击对象
				
				//修改对象属性
				var updateControlInfo = function (){
					$('#pro_id').keydown(function (e){
						if (e.keyCode==13) {
							$(checkObj).attr("id", $(this).val());
						}
					});
					$('#pro_name').keydown(function (e){
						if (e.keyCode==13) {
							$(checkObj).attr("name", $(this).val());
						}
					});
					$('#pro_class').keydown(function (e){
						if (e.keyCode==13) {
							$(checkObj).attr("class", $(this).val());
						}
					});
					$('#pro_value').keydown(function (e){
						if (e.keyCode==13) {
							$(checkObj).attr("value", $(this).val());
						}
					});
					$('#pro_text').keydown(function (e){
						if (e.keyCode==13) {
							$(checkObj).text($(this).val());	
						}
					});
					$('#pro_url').keydown(function (e){
						if (e.keyCode==13) {
							$(checkObj).attr("data-url", $(this).val());	
						}
					});
				}
				
				
				//显示对象属性等信息
				var showControlInfo = function (obj){
					if (obj!=undefined && obj!=null && obj!="") {
						checkObj = obj;
						$('#pro_tagName').val($(obj)[0].tagName.toLowerCase());
						$('#pro_id').val($(obj).attr('id'));
						$('#pro_name').val($(obj).attr('name'));
						$('#pro_class').val($(obj).attr('class'));
						$('#pro_value').val($(obj).attr('value'));
						$('#pro_text').val($(obj).text());
						$('#pro_url').val($(obj).attr('data-url'));
						updateControlInfo();
					}else {
						$('#pro_tagName').val("");
						$('#pro_id').val("");
						$('#pro_name').val("");
						$('#pro_class').val("");
						$('#pro_value').val("");
						$('#pro_text').val("");
						$('#pro_url').val("");
					}
				}
				
				var addClickEvent = function (){
					$('#draw_canvas>form *').on('dblclick', function (e){
						if (dblCheckObj==undefined || dblCheckObj==null || dblCheckObj=="") {
							$(this).addClass('build_check');
							dblCheckObj = this;
						}
						event.stopPropagation();
					});
					
					$(document).on('click', function (e){
						if ($('#draw_canvas').find($(e.target)).length>0) {
							showControlInfo(e.target);
							$(dblCheckObj).removeClass('build_check');
							dblCheckObj = null;
							event.stopPropagation();
						}else {
							if ($('#properties').find($(e.target)).length<=0) {
								showControlInfo(null);
								$(dblCheckObj).removeClass('build_check');
								dblCheckObj = null;
								event.stopPropagation();
							}
						}
					});
					
					$(document).on('keydown', function (e){
						if (e.keyCode==46) {
							$(dblCheckObj).remove();
						};
						event.stopPropagation();
					});
				}
				
				//添加拖拽
				var addEventOnNodes = function(node){
					addClickEvent();
					$(node).draggable({
						stack: "#draw_canvas>.mds_tab_form",
						containment : "#draw_canvas>.mds_tab_form",
						opacity: 0.5,
						cancel: ".title",
						helper: "original"
					});
				}
				
				//为元素添加放置功能
				var addDroppable = function (obj){
					$(obj).droppable({
						greedy:true,
						hoverClass: "draggable_hover",
					    drop : function(event, ui) {
							var node = $('<div class="formField_query"></div>')
									.append(ui.helper[0].innerHTML)
									.addClass(ui.helper[0].className);
							$(node).appendTo($(this));
							addEventOnNodes(node);
							$(node).removeAttr("style");
							$(node).css({"position" : "relative"});
							event.stopPropagation();
							if ($(ui.draggable[0])[0].localName != "li") {
								ui.draggable[0].remove();
							}
					    }
					});
					addClickEvent();
				}
				
				//添加Form表单区域
				$('#btn_addFormDiv').click(function(){
					var length = $('#'+$('#current a:first').attr('tabid')).children("div.inputForm_content").length;
					if (length==undefined || length==null || length<=0) {
						var formDiv = $('<div class="inputForm_content"></div>');
						$('#'+$('#current a:first').attr('tabid')).append(formDiv);
						addDroppable(formDiv);
						addClickEvent();
					}
				});
				
				//添加tab页
				$('#btn_addTabs').click(function (){
					var input_content,tab;
					if ($('#draw_canvas #tabs')!=undefined && $('#draw_canvas #tabs').length!=0) {
						var ul = $('#draw_canvas #tabs');
						var value = ul.attr('class').replace(/[^0-9]/ig,"");
						value = parseInt(value) + 1;
						$(ul).attr("class", "tabs_li_"+value+"tabs");
						
						ul.append('<li><a href="#" tabid="tab'+value+'">tab'+value+'</a></li>');
						
						input_content = $('<div class="inputForm_content"></div>').append('tab'+value);
						tab = $('<div id="tab'+value+'"></div>').append(input_content).css("min-height", "200px");
						$('#draw_canvas>.mds_tab_form #content').append(tab);
					}else {
						var ul = $('<ul id="tabs"></ul>').addClass('tabs_li_1tabs');
						ul.append('<li><a href="#" tabid="tab1">tab1</a></li>');
						
						input_content = $('<div class="inputForm_content"></div>').append('tab1');
						tab = $('<div id="tab1"></div>').append(input_content).css("min-height", "200px");
						var content = $('<div id="content"></div>').append(tab);
						$('#draw_canvas>.mds_tab_form').append(ul).append(content);
					}
					tabsInit();
					addDroppable(input_content);
					addDroppable(tab);
				})
				
				//初始化tab页点击事件
				var tabsInit = function (){
					if ($('#draw_canvas>.mds_tab_form #current')==undefined || $('#draw_canvas #current').length==0) {
						$("#draw_canvas>.mds_tab_form #tabs li:first").attr("id", "current");
					}else {
						$('#draw_canvas>.mds_tab_form #content').children(':last').hide();
					}
					$('#draw_canvas>.mds_tab_form #tabs a').click(function(e) {
						$("#draw_canvas>.mds_tab_form #tabs li").not(this).attr("id", "");
						$('#draw_canvas>.mds_tab_form #content').children().hide();
						$(this).parent().attr("id", "current");
						$('#draw_canvas>.mds_tab_form #' + $(this).attr('tabid')).show();
					})
				}
				
				//初始化tab页点击事件
				var tabsInit2 = function (){
					if ($('#draw_canvas>.mds_tab_form #current')==undefined || $('#draw_canvas #current').length==0) {
						$("#draw_canvas>.mds_tab_form #tabs li:first").attr("id", "current");
					}else {
						//$('#draw_canvas>.mds_tab_form #content').children(':last').hide();
					}
					$('#draw_canvas>.mds_tab_form #tabs a').click(function(e) {
						$("#draw_canvas>.mds_tab_form #tabs li").not(this).attr("id", "");
						$('#draw_canvas>.mds_tab_form #content').children().hide();
						$(this).parent().attr("id", "current");
						$('#draw_canvas>.mds_tab_form #' + $(this).attr('tabid')).show();
					})
				}
				
				//添加按钮栏
				$("#btn_addButtonToolbar").click(function(){
					//判断是否已有按钮栏
					var buttonToolBar = $(".draw_canvas>.mds_tab_form").find('div[id^="commanButtonsDiv"]');
					if(buttonToolBar.length <= 0){
						var node = $("<div id=\"commanButtonsDiv\" class=\"iemes_style_commanButtonsDiv\"> </div>");
						$(node).prependTo($("#draw_canvas>.mds_tab_form"));
						addDroppable(node);
					}else{
						$.MsgBox.Alert("系统提示","按钮栏已存在,不可重复添加");
					}
				});
				
				//添加按钮
				$("#btn_addButton").click(function(){
					//判断是否已有按钮栏
					var buttonToolBar = $(".draw_canvas>.mds_tab_form").find('div[id^="commanButtonsDiv"]');
					if(buttonToolBar.length <= 0){
						$.MsgBox.Alert("系统提示","按钮栏不存在,不可添加添加按钮");
					}else{
						var node = $("<input type=\"button\" value=\"按钮\">");
						$(node).appendTo($("#commanButtonsDiv"));
						$("#commanButtonsDiv").append("&nbsp;")
						addClickEvent();
					}
				});
				
				//添加检索、保存、清除、删除按钮
				$("#btn_addSearchButton, #btn_addSaveButton, #btn_addCleanButton, #btn_addDelButton").click(function(){
					//判断是否已有按钮栏
					var buttonToolBar = $(".draw_canvas>.mds_tab_form").find('div[id^="commanButtonsDiv"]');
					if(buttonToolBar.length <= 0){
						$.MsgBox.Alert("系统提示","按钮栏不存在,不可添加添加按钮");
					}else{
						var id = $(this).attr('id').replace("add","").replace("Button","").toLowerCase();
						var text = $(this).text().replace("添加","").replace("按钮","");
						if (text=="保存") {
							var node = $('<input type="submit" id="'+id+'" value="'+text+'" readonly="readOnly">');
						}else {
							var node = $('<input type="button" id="'+id+'" value="'+text+'" readonly="readOnly">');
						}
						$(node).appendTo($("#commanButtonsDiv"));
						$("#commanButtonsDiv").append("&nbsp;")
						addClickEvent();
					}
				});
				
				//添加查询区域
				$('#btn_addSearchDiv').click(function (){
					if ($('#draw_canvas>.mds_tab_form .inputForm_query')!=undefined && $('#draw_canvas>.mds_tab_form .inputForm_query').length>0) {
						$.MsgBox.Alert("系统提示","该页面已存在查询块，无需重复添加");
						return;
					}else {
						var obj = $('<div class="inputForm_query"></div>');
						if ($('#draw_canvas>.mds_tab_form #tabs')!=undefined && $('#draw_canvas>.mds_tab_form #tabs').length>0) {
							$('#draw_canvas>.mds_tab_form #tabs').before(obj);
						}else {
							$('#draw_canvas>.mds_tab_form').append(obj);
						}
						addDroppable(obj);
					}
				});
				
				
				//页面保存
				$("#btnSavePageSource").click(function(){
					
					var page_name = $("#tbx_page_name").val();
					if (page_name==undefined || page_name==null || page_name=="") {
						$.MsgBox.Alert("系统提示","页面名称不能为空");
						return;
					}
					
					//页面源数据保存
					var url = rootPath + '/builder/builder/page_source_save.shtml';
					var data = "";
					var dataSaveMessage = "";
					//页面数据
					data = "page_source=" + $("#draw_canvas")[0].innerHTML;
					data = data.replace(/\&/g,"%26");
					data = data + "&page_name=" + $("#tbx_page_name").val();
					data = data + "&page_res_id=" + $("#select_menu_parent_id").val();
					// .replace(/"/g,"'");
					$.ajax({
				        url:url,
				        dataType: 'json',
				        async: false,//默认异步调用 false：同步
				        data:data,
				        type:'POST',
				        success:function(data){
				        	dataSaveMessage = data;
				        }
				    });
					if (dataSaveMessage != null && dataSaveMessage!="") {
						if($.parseJSON(dataSaveMessage).status){
							$.MsgBox.Alert("系统提示","保存成功");
						}else{
							$.MsgBox.Alert("系统提示","保存失败");
						}
						
					} else {
						$.MsgBox.Alert("系统提示","保存失败");
					}			
				});
				
				//下载文件
				$('#btnSavePageFile').click(function(){
					var page_name = $("#tbx_page_name").val();
					if (page_name==undefined || page_name==null || page_name=="") {
						$.MsgBox.Alert("系统提示","请先检索需要生成的界面");
						return;
					}
					var url = rootPath + '/builder/builder/generateJspCode.shtml';
					var form = $("<form></form>").attr("action", url).attr("method", "post");
			        form.append($("<input></input>").attr("type", "hidden").attr("name", "page_name").attr("value", $("#tbx_page_name").val()));
			        form.appendTo('body').submit().remove();
			        
			        setTimeout(() => {
			        	var url = rootPath + '/builder/builder/generateJsCode.shtml';
						var form = $("<form></form>").attr("action", url).attr("method", "post");
				        form.append($("<input></input>").attr("type", "hidden").attr("name", "page_name").attr("value", $("#tbx_page_name").val()));
				        form.appendTo('body').submit().remove();
					}, 1000);
				});
				
				//页面查询
				$("#btnQueryPageSource").click(function(){
					
					var page_name = $("#tbx_page_name").val();
					if (page_name==undefined || page_name==null || page_name=="") {
						$.MsgBox.Alert("系统提示","页面名称不能为空！");
						return;
					}
					//页面源数据保存
					var url = rootPath + '/builder/builder/query_page_source.shtml';
					var data = "";
					var out_data = "";
					var page_source = "";
					var dataPMenuId = "";
					//页面数据
					data = "page_name=" + $("#tbx_page_name").val();
					// .replace(/"/g,"'");
					$.ajax({
				        url:url,
				        dataType: 'json',
				        async: false,//默认异步调用 false：同步
				        data:data,
				        type:'POST',
				        success:function(data){
				        	out_data = data;
				        }
				    });
										
					if (out_data != null) {
						page_source = $.parseJSON(out_data).result[0];						
						var draw_page = page_source;
						$("#draw_canvas").html(draw_page);
						tabsInit2();
						addDroppable($('.ui-droppable'));
						addEventOnNodes($('.formField_query'));
						
						dataPMenuId = $.parseJSON(out_data).result[1];
						bindResMenu(dataPMenuId);	
						
					}else {
						$.MsgBox.Alert("系统提示","获取页面源数据信息错误，请联系管理员！");
					}
					
					
				});	
				
				//定义拖拽和菜单动作
				$('.operation_menu>li>a').click(function (){
					$(this).parent().children("ul").toggle();
				});
				
				//左侧拖拽操作及画线
				$("ul.operation_menu>li>ul>li").draggable({
					containment : "#draw_canvas",
					cursor: "move",
					opacity : 0.5,
					cursorAt: { top: 5, left: 20 },
					helper: function(e) {
						var className = e.currentTarget.className.replace(" ui-draggable","");
						if (className=="node button") {
							return $("<div class=\"ui_widget_content\"><input type=\"button\" value=\""+e.currentTarget.innerText+"\"></div>");
						}else if (className=="node label"){
							return $("<div class=\"ui_widget_content\"> <label>"+e.currentTarget.innerText+"</label></div>");
						}else if (className=="node textbox"){
							return $("<div class=\"ui_widget_content\"><input type=\"text\" value=\""+e.currentTarget.innerText+"\"></div>");
						}else if (className=="node checkbox"){
							return $("<div class=\"ui_widget_content\"><input type=\"checkbox\">"+e.currentTarget.innerText+"</div>");
						}else if (className=="node dropdownlist"){
							return $("<div class=\"ui_widget_content\"><select><option>"+ e.currentTarget.innerText +"</option></select></div>");
						}else if (className=="node label_input"){
							return $("<div class=\"ui_widget_content\"><label>标签:</label><input type='text'></div>");
						}else if (className=="node label_search_input"){
							return $('<div class="ui_widget_content"><label>标签:</label><input type="text">&nbsp;<input type="button" submit="N" value="检索" onclick="operationBrowse(this)"></div>');
						}else if (className=="node label_search_input_ver"){
							return $('<div class="ui_widget_content"><label>标签:</label><input type="text">&nbsp;<input type="text" class="form_version">&nbsp;<input type="button" submit="N" value="检索" onclick="operationBrowse(this)"></div>');
						}else if (className=="node label_checkBox"){
							return $('<div class="ui_widget_content"><label>标签:</label><select><option>是</option></select></div>');
						}else if (className=="node label_label"){
							return $('<div class="ui_widget_content"><label>标签:</label><span>值</span></div>');
						}else if (className=="node tabel"){
							return $('<div class="ui_widget_content">' +
									'<table class="mtable">'+
										'<tr>'+
											'<th>col1</th>'+
											'<th>col2</th>'+
										'</tr>'+
									'</table>'+
									'</div>');
						}
					}
				});
				addClickEvent();
			}

			//2、创建画布
			var createCanvas = function (){
				var canvas = $('<div class="canvas_middle"></div>')
					.append($('<div class="draw_canvas" id="draw_canvas"></div>')
							.append('<form class="mds_tab_form"></form>'));
				$("#"+pageId).append(canvas);
			};

			//3、创建属性栏
			var createPropertices = function (){
				$("#build_properties li:first").attr("class", "tab_check");
				$('#centent').children(':not(:first)').hide();
				
				$("#build_properties>li").on("click",function() {
					$("#build_properties li").not(this).attr("class", "");
					$('#centent').children().hide();
					$(this).attr("class", "tab_check");
					$('#' + $(this).children('a:first').attr('tabid')).show();
				});
				
			};

			//4、创建工具栏 在其他事件之前调用
			var createTools = function (){
				$('.iedex_subheader_sop').hide();
				var toolBarStr = "<div class=\"div_page_save\" id=\"div_builder_page_toolbar\">"
					
							   + "<label>页面名称:</label>"	
							   + "<input type=\"text\" "
							   + "dataValue=\"page_name\" "
							   + "relationId=\"tbx_page_id\" "
							   + "viewTitle=\"菜单\" "
							   + "data-url=\"/popup/queryAllBuilderPage.shtml\"  "
							   + "class=\"formText_query majuscule\" id=\"tbx_page_name\" /> "
							   + "<input type=\"hidden\" id=\"tbx_page_id\" dataValue=\"id\" value=\"${resFormMap.id }\"> "
							   + "<input type=\"button\"  class = \"search_button\" submit=\"N\" value=\"检索\"  onclick=\"operationBrowse(this)\"  textFieldId=\"tbx_page_name\"> "
							   
							  /* + "<label>关联菜单:</label> "
							   + "<input type=\"text\" "
							   + "dataValue=\"res_key\"  "
							   + "relationId=\"tbx_res_id\" "
							   + "viewTitle=\"菜单\" "
							   + "data-url=\"/popup/queryAllMenu.shtml\"  "
							   + "class=\"formText_query majuscule\" id=\"tbx_res_key\" /> "
							   + "<input type=\"hidden\" id=\"tbx_res_id\" dataValue=\"id\" value=\"${resFormMap.id }\"> "
							   + "<input type=\"button\"  class = \"search_button\" submit=\"N\" value=\"检索\"  onclick=\"operationBrowse(this)\"  textFieldId=\"tbx_res_key\"> "*/
							   
							   + "<label>关联菜单:</label> "
							   + "<select class=\"formText_query\" id=\"select_menu_parent_id\"> "
							   + "</select> "
							  		                    
							   + "<input type=\"button\" class=\"div_page_save_button\" id=\"btnQueryPageSource\"  value=\"查询\"> "
							   + "<input type=\"button\" class=\"div_page_save_button\" id=\"btnSavePageSource\"  value=\"保存\"> "
							   + "<input type=\"button\" class=\"div_page_save_button\" id=\"btnSavePageFile\"  value=\"生成文件\"> "
							   + "</div> ";
			   var toolBar = $(toolBarStr);	
			   $("#div_builder_page_toolbar").remove();
			   $(".index_subheader").append(toolBar);	
			   
			   bindResMenu("");		  		   
		};
		
		var bindResMenu = function(selltctResId){
		////绑定上层菜单列表
			var url = rootPath + '/system/menu/menu_list.shtml';
			var dataPMenu = "";
			var data = "";
			$.ajax({
		        url:url,
		        dataType: 'json',
		        async: false,//默认异步调用 false：同步
		        data:data,
		        type:'POST',
		        success:function(data){
		        	dataPMenu = data;
		        }
		    });
			if (dataPMenu != null) {
				var currPMenu = selltctResId;
				var h = "<option value='0'>------顶级目录------</option>";
				for ( var i = 0; i < dataPMenu.length; i++) {
						if ($.trim(dataPMenu[i].type) != "2") {
							if ($.trim(currPMenu) == $.trim(dataPMenu[i].id)) {
								h += "<option selected=\"selected\" value='"
										+ dataPMenu[i].id + "'>"
										+ dataPMenu[i].res_name + "</option>";
							} else {
								h += "<option value='" + dataPMenu[i].id + "'>"
										+ dataPMenu[i].res_name + "</option>";
							}
						}
				}
				$("#select_menu_parent_id").html(h);
			} else {
				showErrorNoticeMessage("获取菜单信息错误，请联系管理员！");
			}
		}
		
		init();
		}
	}
})();